package exam.axhu.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import exam.axhu.entity.Choice;
import exam.axhu.entity.Teacher;
import exam.axhu.service.TeacherService;

@Service @Transactional
public class TeacherServiceImpl implements TeacherService{
//defaltBean: teacherServiceImpl
	@Resource SessionFactory factory;
	
	public int save(Teacher teacher) {
		if(this.find(teacher.getTeacherID())!=null)
			return 1;   //用户已存在
		else{
			factory.getCurrentSession().persist(teacher);
			return 0;   //成功保存用户
		}
	}
	
	/*public int save(Teacher teacher){
		factory.getCurrentSession().persist(teacher);
		return 0; 
		
	}*/


	public void delete(String... teacherIDs) {
		for(String teacherID : teacherIDs){
			if(this.find(teacherID)!=null)
				factory.getCurrentSession().delete(factory.getCurrentSession().load(Teacher.class,teacherID));
		}
		
	}


	public void update(Teacher teacher) {
		factory.getCurrentSession().merge(teacher);
		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Teacher find(String teacherID) {
		/*if( (Teacher) factory.getCurrentSession().get(Teacher.class,teacherID)!=null)
			return (Teacher) factory.getCurrentSession().get(Teacher.class,teacherID);
		else return null;*/
		return (Teacher) factory.getCurrentSession().get(Teacher.class,teacherID);
	}
	
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Teacher> findByName(String name){
			//条件查询，自定义索引名(参数名):username,:password.通过setString,setParameter设置参数   
			Query query = factory.getCurrentSession().createQuery("from Teacher as c where c.name = :searchName ");
			query.setString("searchName", name);
			return query.list();
	        
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Teacher> list() {
		return factory.getCurrentSession().createQuery("from Teacher").list();
	}

}
